package com.leiyuee.flink.tools;

import lombok.extern.slf4j.Slf4j;
import org.apache.flink.table.data.RowData;

import java.math.BigDecimal;

@Slf4j
public class StatementUtil {
    public static String subValue(String index, RowData rowData, int valueIndex, int maxLength) {
        String result = String.valueOf(rowData.getString(valueIndex));
        if (result != null && !result.equals("")) {
            if(result.length() > maxLength) {
                result = result.substring(0, maxLength);
                log.warn("{} 发生数据截断, statement Index：{}, 字节长度超过数据库长度，已截取数据库支持最大长度[{} 字节]", index, valueIndex + 1, maxLength);
            }
            return result;
        }
        return null;
    }

    public static String doubleToString(String index, RowData rowData, int valueIndex, int maxLength) {
        String result = String.valueOf(rowData.getDouble(valueIndex));
        if (!result.equals("")) {
            if(result.length() > maxLength) {
                result = result.substring(0, maxLength);
                log.warn("{} 发生数据截断, statement Index：{}, 字节长度超过数据库长度，已截取数据库支持最大长度[{} 字节]", index, valueIndex + 1, maxLength);
            }
            return result;
        }
        return null;
    }

    public static BigDecimal stringToBigDecimal(String index, RowData rowData, int valueIndex) {
        String result = String.valueOf(rowData.getString(valueIndex));
        // 判断 result 是否为数值类型的字符串 result.matches("-?\\d+(\\.\\d+)?")
        if (result != null && !result.equals("")) {
            if (!result.matches("-?\\d+(\\.\\d+)?")) {
                log.warn("{} 发生数据类型转换错误[String => BigDecimal], statement Index：{}, String 值[{}]为非数值类型字符串", index, valueIndex + 1, result);
                return BigDecimal.ZERO;
            } else if(result.matches("\\d+(\\.\\d+)?")) {
                log.warn("{} 存在小数[String => BigDecimal], statement Index：{}, 值[{}]", index, valueIndex + 1, result);
                return BigDecimal.ZERO;
            }
            return new BigDecimal(result);
        }
        return BigDecimal.ZERO;
    }

}
